import axios from 'axios'

// const API_BASE_URL = 'http://ddns.6010.top:12803/api'
const API_BASE_URL = 'http://127.0.0.1:8123/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
})

/**
 * 获取聊天历史记录
 * @param {string} chatId - 聊天ID
 * @returns {Promise<Array>} - 历史消息数组
 */
export const getChatHistory = async (chatId) => {
  try {
    const response = await apiClient.get(`/ai/chat/memory/redis?chatId=${encodeURIComponent(chatId)}`)
    return response.data
  } catch (error) {
    console.error('Error fetching chat history:', error)
    return []
  }
}

/**
 * 处理SSE连接的函数 - AI旅游攻略专家
 * @param {string} message - 用户消息
 * @param {string} chatId - 聊天ID
 * @param {Function} onMessage - 消息回调函数
 * @param {Function} onComplete - 完成回调函数
 * @returns {EventSource} - SSE连接对象
 */
export const connectToTravelGuideSSE = (message, chatId, onMessage, onComplete) => {
  // 构建URL，包含查询参数
  const url = `${API_BASE_URL}/ai/travel_guide/chat/sse/emitter?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}`
  
  // 创建EventSource对象
  const eventSource = new EventSource(url)
  
  // 监听消息事件
  eventSource.onmessage = (event) => {
    const data = event.data
    if (data === '[DONE]') {
      // 流式响应结束
      eventSource.close()
      if (onComplete) onComplete()
    } else {
      // 处理流式响应数据
      if (onMessage) onMessage(data)
    }
  }
  
  // 监听错误事件
  eventSource.onerror = (error) => {
    console.error('SSE Error:', error)
    eventSource.close()
    if (onComplete) onComplete()
  }
  
  return eventSource
}

/**
 * 处理SSE连接的函数 - AI超级智能体
 * @param {string} message - 用户消息
 * @param {Function} onMessage - 消息回调函数
 * @param {Function} onComplete - 完成回调函数
 * @returns {EventSource} - SSE连接对象
 */
export const connectToManusSSE = (chatId,message, onMessage, onComplete) => {
  // 构建URL，包含查询参数
  const url = `${API_BASE_URL}/ai/manus/chat?message=${encodeURIComponent(message)}&chatId=${encodeURIComponent(chatId)}`
  
  // 创建EventSource对象
  const eventSource = new EventSource(url)
  
  // 监听消息事件
  eventSource.onmessage = (event) => {
    const data = event.data
    if (data === '[DONE]') {
      // 流式响应结束
      eventSource.close()
      if (onComplete) onComplete()
    } else {
      // 处理流式响应数据
      if (onMessage) onMessage(data)
    }
  }
  
  // 监听错误事件
  eventSource.onerror = (error) => {
    console.error('SSE Error:', error)
    eventSource.close()
    if (onComplete) onComplete()
  }
  
  return eventSource
}

/**
 * 停止AI聊天生成
 * @param {string} chatId - 聊天ID
 * @returns {Promise<boolean>} - 是否成功停止
 */
export const stopChat = async (chatId) => {
  try {
    await apiClient.get(`${API_BASE_URL}/ai/travel_guide/chat/stop?chatId=${encodeURIComponent(chatId)}`);
    return true;
  } catch (error) {
    console.error('Error stopping chat:', error);
    return false;
  }
};